package sample.controller.todo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.BeanMap;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;

public class AddController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger =
        Logger.getLogger(AddController.class.getName());

    @Override
    public Navigation run() {

        DatastoreService datastoreService =
            DatastoreServiceFactory.getDatastoreService();
        String content = asString("content");
        if (!StringUtil.isEmpty(content)) {

            // カテゴリ
            Entity category = null;
            String strCategoryKey = asString("category");
            if (StringUtil.isEmpty(strCategoryKey)) {
                // カテゴリがしていされてない時はblankカテゴリで登録
                Query q = new Query("Category");
                q.addFilter("name", Query.FilterOperator.EQUAL, "blank");
                PreparedQuery pq = datastoreService.prepare(q);
                category = pq.asSingleEntity();
                if (category == null) {
                    // blankのカテゴリが登録されてなければ登録する
                    category = new Entity("Category");
                    category.setProperty("name", "blank");
                    Transaction transaction = datastoreService.beginTransaction();
                    try {
                        datastoreService.put(category);
                        transaction.commit();
                    } finally {
                        if (transaction.isActive()) {
                            transaction.rollback();
                        }
                    }
                }
            } else {
                // カテゴリが指定されている場合
                try {
                    category =
                        datastoreService.get(KeyFactory
                            .stringToKey(strCategoryKey));
                } catch (EntityNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            // 保存
            Entity todo = new Entity("Todo", category.getKey());
            todo.setProperty("content", asString("content"));
            todo.setProperty("createdAt", new Date());
            todo.setProperty("done", false);

            Transaction transaction = datastoreService.beginTransaction();
            try {
                datastoreService.put(transaction, todo);
                transaction.commit();
            } finally {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
            }
        }
        
        // カテゴリの取得
        // 検索
        Query q = new Query("Category"); // KIND：Categoryを検索
        PreparedQuery pq = datastoreService.prepare(q);
        List<Entity> result = pq.asList(FetchOptions.Builder.withOffset(0));
        List<BeanMap> list = new ArrayList<BeanMap>();
        for (Entity e: result) {
            BeanMap m = new BeanMap();
            m.put("key", KeyFactory.keyToString(e.getKey()));
            m.put("name", e.getProperty("name"));
            list.add(m);
        }
        requestScope("categories", list);
        return forward("add.jsp");
    }
}
